import { isSupportStorage } from "./tools"
import { assign } from 'lodash'

// 类型 window.localStorage,window.sessionStorage

class Storage {
  config = {
    type: 'localStorage', // 本地存储类型 sessionStorage
    prefix: 'ADMIN', // 名称前缀 建议：项目名
    isEncrypt: false // 默认加密 为了调试方便, 开发过程中可以不加密
  }
  constructor(options) {
    if (options) {
      assign(this.config, options)
      this.storage = window[this.config.type]
    }
  }
  autoAddPrefix (key) {
    let { prefix } = this.config
    prefix = prefix ? prefix + '_' : ''
    return  prefix + key
  }
  remove (key) {
    this.config.storage.removeItem(this.autoAddPrefix(key))
  }
  removeAll () {
    this.config.storage.clear()
  }
  get (key) {
    key = this.autoAddPrefix(key)
    if (!isSupportStorage()) throw Error('浏览器不支持本地存储')
    if (!key) return null
    if (!this.storage.getItem(key)) return null
    const curStorage = JSON.parse(this.storage.getItem(key))
    const { expire, time, value} = curStorage
    const nowTime = +new Date()
    if (expire && expire < (nowTime - time)) {
      this.remove(key)
      return null
    } else {
      return value
    }
  }
  set (key, value, expire = 0) {
    if (!isSupportStorage()) throw Error('浏览器不支持本地存储')
    if (!key) throw new Error("key cannot is empty")
    if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number")
    value = value || null
    const data = {
      value,
      time: +new Date(),
      expire
    }
    assign(this.config, data)
    const string = JSON.stringify(data)
    this.storage.setItem(this.autoAddPrefix(key), string)
  }
}

const storage = new Storage({ type: 'sessionStorage' })
export default storage
